<template>
  <el-dialog 
    class="edit-dialog"
    :visible.sync="isVisible"
    :close-on-click-modal="false"
    :title="title"
    width="600px">
    <el-form
      ref="editForm"
      :model="editForm"
      :rules="rules"
      autocomplete="off"
      label-position="right" 
      label-width="100px"
    >
      <el-form-item prop="userName" label="用户名">
        <el-input
          ref="userName"
          v-model="editForm.userName"
          placeholder="请输入用户名"
          :disabled="isDisabled"
          name="userName"
          type="text"
        />
      </el-form-item>
      <el-form-item prop="roleId" label="所属角色">
        <el-select v-model="editForm.roleId" placeholder="请选择角色" width="100%">
          <el-option
            v-for="item in roleItems"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="areaName" label="所属区域">
        <el-col :span="7">
          <el-input
            ref="areaName"
            disabled
            v-model="editForm.areaName"
            placeholder="请选择区域"
            name="areaName"
            type="text"
          />
        </el-col>
        <el-col :span="15">
          <el-cascader
            ref="cascader"
            class="search-item"
            :props="areaProps"
            @change="handleChange"
            v-model="editForm.areaIds"
            style="width: 300px"
          ></el-cascader>
        </el-col>
      </el-form-item>
      <el-form-item v-if="type=='add'" prop="password" label="密码">
        <el-input
          ref="password"
          v-model="editForm.password"
          placeholder="请输入密码"
          name="password"
          type="password"
        />
      </el-form-item>
      <el-form-item prop="mobile" label="手机号">
        <el-input
          ref="mobile"
          v-model="editForm.mobile"
          placeholder="请输入手机号"
          name="mobile"
          type="text"
        />
      </el-form-item>
      <el-form-item label="数字证书B64">
        <el-input
          ref="signCert"
          v-model="editForm.signCert"
          placeholder="请输入数字证书Base64"
          name="signCert"
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="medium" type="primary" plain @click="getCert">获取证书</el-button>
      <el-button size="medium" @click="isVisible=false">取 消</el-button>
      <el-button size="medium" type="primary" :loading="submitLoading" @click="editSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {insertUser, updateUser,selectRolePage, commAreaUrl, commUserAreaEx, getUser } from '@/http/apiUrls.js';
import {GZCA} from "@/utils/gzca";
import * as token from '@/utils/auth.js'
export default {
  name: 'EditForm',
  props: {
    // 弹窗显示
    dialogVisible: { type: Boolean, default: false},
    // 弹窗类型
    type: { type: String, default: "add" }
  },
  computed: {
    // 控制显示
    isVisible: {
      get() { 
        return this.dialogVisible; 
      },
      set() {
        this.$refs['editForm'].resetFields();
        this.editForm = this.initEditObj()
        this.$emit('close')
      }
    },
    // 标题
    title:{
      get(){
        if(this.type == 'add'){
          return '添加用户'
        }else{
          return '修改用户'
        }
      }
    },
    isDisabled:{
      get(){
        if(this.type == 'add'){
          return false
        }else{
          return true
        }
      }
    }
  },
  mounted(){
    this.getRoleItems()
  },
  data() {
    let checkPasswordFormat = (rule, value,callback) => {
      // 必须有数字、字母
      let reg = /^(?=.*[0-9])(?=.*[a-zA-Z]).{8,20}$/;
      if(!reg.test(value)){
        return callback(new Error("密码必须由8~20位的数字、字母（区分大小写）组成"));
      }
      // 不能有空格
      let spaceReg = new RegExp(/\s+/g);
      if(spaceReg.test(value)){
        return callback(new Error("密码不可包含空格，请重新输入"));
      }
      return callback();
    }
    
    return {
      submitLoading:false,
      editForm: this.initEditObj(),
      roleItems: [],
      rules: {
        userName: {
          required: true,
          message: '请输入用户名',
          trigger: "blur"
        },
        mobile: {
          required: true,
          message: '请输入电话号码',
          trigger: "blur"
        },
        roleId: {
          required: true,
          message: '请选择所属角色',
          trigger: "blur"
        },
        areaName: {
          required: true,
          message: '请选择所属区域',
          trigger: "blur"
        },
        password: [{
          required: true,
          message: '请输入密码',
          trigger: "blur"
        },{
          validator:checkPasswordFormat,trigger:"blur"
        }]
      },
      areaProps: { 
        lazy: true,
        checkStrictly: true,
        lazyLoad: (node, resolve) => { 
          const { level } = node; 
          const nodes = [];
          // 拿取贵州省内数据
          // let type = level == 0 ? "520000000000" : node.value;
          // 拿取贵州  省级数据
          let type = level == 0 ? null : node.value;
          this.provinceFn(type) 
            .then((res) => {
              // 节点数组
              res.map((item) => {
                let obj = {
                  value: item.code,
                  label: item.fullName,
                  leaf: item.level >= 4
                };
                nodes.push(obj);
                // 省级数据同时是一级菜单
                // if(item.code ==520000000000 && item.level == 1){
                //   let obj = {
                //     value: item.code,
                //     label: item.fullName,
                //     leaf: item.level >= 3
                //   };
                //   nodes.push(obj);
                // }
                // if(item.level != 1 ){
                //   let obj = {
                //     value: item.code,
                //     label: item.fullName,
                //     leaf: item.level >= 3
                //   };
                //   nodes.push(obj);
                // }
              });
              // resolve 节点返回
              resolve(nodes);
            })
            .catch((error) => {
              console.log(error);
            });
        }
      }
    }
  },
  methods: {
    // 修改传递值
    setEditObj(val) {
      this.editForm = {...val};
    },
    // 重置值
    initEditObj(){
      return {
        userName: "",
        mobile: "",
        password: "",
        roleId: '',
        areaCode: '',
        areaName: '',
        areaIds: [],
        signCert: "",
      }
    },
    getRoleItems(){
      let requestData = {
        current: 1,
        size : 100,
        model: {}
      }

      let tokenUser = token.getUserInfo();
      if(tokenUser){
        // 查询用户信息
        let userId = tokenUser.userId
        let url = getUser+userId
        this.$getJson(url).then(res => {
          if(res){
            // 获取角色列表
            let areaCode = res.areaCode;
            if(areaCode != '520000000000'){
              requestData.model.id = res.roleId
            }
            this.$postJson(selectRolePage, requestData).then(res => {
              if(res){
                this.roleItems = res.records;
              }
            })
          }
        })
      }
      
    },
    // 监听数据变化
    handleChange(value) {
      const checkNodes = this.$refs.cascader.getCheckedNodes();
      if(checkNodes && checkNodes.length > 0){
        const checkNode = checkNodes[0]
        this.editForm.areaCode = checkNode.value;
        this.editForm.areaName = checkNode.label;
      }
      console.log(value);
    },
    getArea(code){
      return new Promise((resolve, reject) => {
        const requestData = {
          parentCode: code
        }
        if(code){
          this.$postJson(commAreaUrl, requestData).then(res => {
            if(res){
              resolve(res)
            }else{
              resolve([])
            }
          })
        }else{
          this.$postJson(commUserAreaEx, {}).then(res => {
            if(res){
              resolve(res)
            }else{
              resolve([])
            }
          })
        }
      })
    },
    // 获取省市区街道
    provinceFn(code) {
      // console.log("-----省市区------",code);
      // 此处是一个promise 直接返回
      return this.getArea(code);
    },
    editSubmit(){
       this.$refs.editForm.validate(valid => {
        if (valid) {
          if(this.type === 'add'){
            this.insert()
          }else{
            this.edit()
          }
        } else {
          return false;
        }
      });
    },
    insert(){
      let requestData = this.editForm;
      console.log(requestData);
      this.submitLoading = true;
      this.$postJson(insertUser, requestData).then(res => {
        this.submitLoading = false;
        if(res){
          this.$message({
            type: 'success',
            message: '添加成功!'
          });
          this.isVisible = false;
          this.$emit('success')
        }
      })
    
    },
    edit(){
      let requestData = this.editForm;
      console.log("---requestData-----",requestData);
      this.submitLoading = true;
      this.$postJson(updateUser, requestData).then(res => {
        this.submitLoading = false;
        if(res){
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          this.isVisible = false;
          this.$emit('success')
        }
      })
    },
    // 获取证书b64
    getCert(){
      GZCA.init(res=>{
        if(!res){
          this.$message({
            type: 'error',
            message: '连接客户端失败',
          })
          return;
        }
        this.getCertList();
      })
    },
    // 获取证书列表
    getCertList(){
      const certType = 1;
      GZCA.GZCA_GetCertList(true, certType, res=>{
        if(!res.success){
          this.$message({
            type: 'error',
            message: res.msg,
          })
          return;
        }
        this.getCertB64(res.ContainerName, certType);
      })
    },
    // 获取证书
    getCertB64(containerName, certType){
      GZCA.GZCA_ExportCert(containerName, certType, res=>{
        if(!res.success){
          this.$message({
            type: 'error',
            message: res.msg,
          })
          return;
        }
        this.editForm.signCert = res.CertB64;
      })
    },
  }
}
</script>
<style lang="scss">
.edit-dialog{
  .el-dialog__header{
    padding: 15px 20px 15px;
    .el-dialog__title{
      color: #fff;
    }

    i{
      color: #fff;
    }
    
    background-color: #006ACC;
  }

  .el-dialog__footer{
    padding: 15px 20px 15px;
    border-top: 1px solid #dfe4ea;
  }
}
</style>